package com.example.proj_kefei.Controller;

import com.example.proj_kefei.Util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Api("图片上传")
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${upload.filePath}")
    private String filePath;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {
        if (file == null) {
            return new Result(200,"参数文件为空",null);
        }
        String fileName = file.getOriginalFilename();
        String fileExtension = fileName.substring(fileName.lastIndexOf('.')).toLowerCase();
        String saveFileName = System.currentTimeMillis() + fileExtension;

        File directory = new File(filePath);
        if (!directory.exists()) {
            directory.mkdir();
        }

        File targetFile = new File(directory,saveFileName);
        try{
            file.transferTo(targetFile);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return new Result(200,"上传成功，返回图片地址","/images/"+saveFileName);
    }

}
